const Service = require("egg").Service;
const axios = require("axios");

class WxpublickService extends Service {

  async getPublicList(mywxid, field, page, pageSize){
    const { ctx } = this;
    try {
      const fields = {
        ownerWxid: mywxid,
        ...field
      }
      // 计算跳过的文档数量
      const skip = (page - 1) * pageSize;
      
      // 获取总数
      const total = await ctx.model.Wxpublick.countDocuments(fields);
      
      // 使用 skip 和 limit 实现分页查询
      const data = await ctx.model.Wxpublick.find(fields)
        .skip(skip)
        .limit(pageSize)
        .exec();
  
      return {
        code: 20000,
        msg: '获取成功',
        data: {
          count: total,
          list: data
        }
      };
    } catch (error) {
      // 捕获异常并返回错误信息
      this.logger.error("获取公众号信息失败:", error.message);
      return {
        code: 50000,
        msg: "请求失败，请检查网络或接口状态",
        data: {
          count: 0,
          list: []
        }
      };
    }
  }
  async updatePublickList(mywxid) {
    const { ctx } = this;
    await ctx.model.Wxpublick.deleteMany({});
    try {
      // 调用外部接口获取当前登录微信用户信息
      const response = await axios.post(
        this.config.baseURL,
        {
          type: "getPublicList",
          data: {
            type: "2",
          },
        },
        {
          params: { mywxid }, // 将 wxid 作为 Params 参数传递
        }
      );

      // 好友列表数据
      const datalist = response.data.result;

      await Promise.all(
        datalist.map((publick) =>
          ctx.model.Wxpublick.create({
            ownerWxid: mywxid,
            wxid: publick.wxid || "",
            nick: publick.nick || "",
            wxNum: publick.wxNum || "",            
            v3: publick.v3 || "",
            avatarMinUrl: publick.avatarMinUrl || "",
            avatarMaxUrl: publick.avatarMaxUrl || "",
          })
        )
      );
      return datalist;
      
    } catch (error) {
      // 捕获异常并返回错误信息
      this.logger.error("获取用户信息失败:", error.message);
      return {
        success: false,
        message: "请求失败，请检查网络或接口状态",
      };
    }
  }
  // 修改数据
  async editPublick(mywxid, wxid, field) {
    const { ctx } = this;
    try {
      const result = await ctx.model.Wxpublick.findOneAndUpdate(
        { ownerWxid: mywxid, wxid: wxid },
        { $set: field },
        { new: true }
      );
      
      if (!result) {
        throw new Error('未找到该好友');
      }
      
      return result;
    } catch (error) {
      this.logger.error("更新好友状态失败:", error);
      throw error;
    }
  }
}
module.exports = WxpublickService;
